<script setup>
import {reactive, ref, toRaw} from "vue";
import {Edit, Plus, RefreshLeft, Search} from "@element-plus/icons-vue";
import api from "@/util/api";
import {onMounted} from "vue";
import baseUrl from "@/util/constant.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {getJwt} from "@/api/jwt.js";
import {removeJwt} from "../../api/jwt.js";
import router from "../../router/index.js";

onMounted(async () => {
  onSubmit();
})
let refSearchForm = ref();
let tableData = ref();
let adminPi = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0
});
let searchForm = ref({
  name: null,
  username: null
});
let dialogFormVisible = ref(false);
let dialogFormTitle = ref("添加管理员");
let dialogFormData = ref({
  name: null,
  username: null,
  password: null,
  avatar: null
})
let dialogForm = ref();
let model = "add"

const headers = {
  "jwt": getJwt()
}

//查询
async function onSubmit(pageNo = 1, pageSize = 10) {
  let params = toRaw(searchForm.value);
  // console.log(params);
  // console.log("======================")
  let resp = await api({
    url: "/admin",
    method: "get",
    params: {
      pageNo,
      pageSize,
      ...params,
    }
  });
  //console.log(resp);
  tableData.value = resp.data.records;
  adminPi.total = resp.data.total;
  adminPi.pageNo = resp.data.current;
  adminPi.pageSize = resp.data.size;

}

//页码变化
function handleCurrentChange(pageNo, pageSize) {
  onSubmit(pageNo, pageSize);
}

//重置按钮
function reset() {
  console.log("重置:" + refSearchForm);
  refSearchForm.value.resetFields();
  onSubmit();
}

//添加按钮
function add() {
  dialogFormVisible.value = true;
  dialogFormTitle.value = "添加管理员";
  dialogFormData.value = {
    name: null,
    username: null,
    password: null,
    avatar: null
  }
  model = "add";
}

//编辑按钮
function handleEdit(row) {
  dialogFormVisible.value = true;
  dialogFormTitle.value = "编辑管理员";
  dialogFormData.value = {
    id: row.id,
    name: row.name,
    username: row.username,
    password: row.password,
    avatar: row.avatar
  }
  model = "edit";
}

function doUpdate() {
  if (model === "add") {
    submitAdd();
  } else {
    submitEdit();
  }
}

//提交更新
function submitAdd() {
  let params = toRaw(dialogFormData.value);
  console.log(params);
  api({
    url: "/admin",
    method: "post",
    data: params
  }).then(resp => {
    if (resp.success) {
      dialogFormVisible.value = false;
      onSubmit();
    } else {
      ElMessage.error(resp.msg || "新增失败")
    }
  })
}

//提交编辑
function submitEdit() {
  let params = toRaw(dialogFormData.value);
  api({
    url: "/admin",
    method: "put",
    data: params
  }).then(resp => {
    if (resp.success) {
      dialogFormVisible.value = false;
      onSubmit(adminPi.pageNo, adminPi.pageSize)
      ElMessage.success("编辑成功");
    } else {
      ElMessage.error(resp.msg || "编辑失败")
    }
  })
}


function handleAvatarSuccess(resp) {
  dialogFormData.value.avatar = resp.data;
}

//头像上传前验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('只能上传JPG/PNG格式的图片!');
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!');
  }
  return isJPG && isLt2M;
};

//删除按钮
function handleDelete(row) {
  ElMessageBox.confirm(
      '是否确认删除',
      '警告',
      {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning',
      }
  ).then(() => {
    let id = row.id
    api({
      url: "/admin",
      method: "delete",
      data: JSON.stringify(id),
      headers: {
        'Content-Type': 'application/json'
      }
    }).then(resp => {
      if (resp.success) {
        ElMessage.success("删除成功");
        onSubmit(adminPi.pageNo, adminPi.pageSize)
      } else {
        ElMessage.error(resp.msg || "删除失败")
      }
    });
  }).catch(() => {
    ElMessage.info('已取消删除');
  })
}

const rules = {
  username: [
    {required: true, message: '请输入账号', trigger: 'blur'},
  ],
  oldPassword: [
    {required: true, message: '请输入密码', trigger: 'blur'},
  ],
  newPassword: [
    {required: true, message: '请输入密码', trigger: 'blur'},
  ],
}
let editPwForm = ref({
  username: null,
  oldPassword: null,
  newPassword: null,
  confirmPassword: null
})
let editPwDialogVisible = ref(false);
let editPwFormModel = ref();
//修改密码按钮
function editPassword(row){
  editPwDialogVisible.value = true;
  editPwForm.value={
    username:row.username
  }
}
//修改密码提交
function subEditPw(){
  let params = toRaw(editPwForm.value);
  api({
    url: "/admin/password",
    method: "put",
    data: params
  }).then(resp => {
    if (resp.success) {
      ElMessage.success("修改成功");
      editPwDialogVisible.value = false;
      logout();
    } else {
      ElMessage.error(resp.msg || "修改失败")
    }
  })
}
function logout(){
  removeJwt();
  //刷新页面
  router.push('/login').then(() => {
    window.location.reload();
  });
}


</script>

<template>
  <!--搜索区域-->
  <div class="search-region">
    <el-form :inline="true" :model="searchForm" class="demo-form-inline" ref="refSearchForm">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable/>
      </el-form-item>
      <el-form-item label="账号" prop="username">
        <el-input v-model="searchForm.username" placeholder="请输入账号" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit()" :icon=Search>查询</el-button>
        <el-button @click="reset" :icon=RefreshLeft>重置</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="addAdmin">
    <el-button type="primary" @click="add" :icon=Plus>添加管理员</el-button>
  </div>
  <!--表格区域-->
  <div class="grid">
    <el-table :data="tableData" stripe style="width: 100%" border highlight-current-row>
      <el-table-column prop="id" label="ID" width="130"/>
      <el-table-column prop="avatar" label="头像" width="180">
        <template #default="scope">
          <div class="AdImages" :style="'background-image: url('+scope.row.avatar+')'"></div>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="Name" width="150"/>
      <el-table-column prop="username" label="账号"/>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" size="default" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="default" @click="handleDelete(scope.row)">删除</el-button>
          <el-button type="warning" size="default" @click="editPassword(scope.row)">修改密码</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!--分页区域-->
  <div class="demo-pagination-block">
    <el-pagination
        v-model:current-page="adminPi.pageNo"
        v-model:page-size="adminPi.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :size="'default'"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total=adminPi.total
        @change="handleCurrentChange"
    />
  </div>
  <!--弹窗区-->
  <div>
    <el-dialog v-model="dialogFormVisible" :title="dialogFormTitle" width="500">
      <el-form :model="dialogFormData" ref="dialogForm">
        <el-row>
          <el-col :span="14">
            <div class="grid-content ep-bg-purple">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="dialogFormData.name" autocomplete="off"/>
              </el-form-item>
              <el-form-item label="账号" prop="username">
                <el-input v-model="dialogFormData.username" autocomplete="off"/>
              </el-form-item>
              <el-form-item label="密码" prop="password" v-if="model==='add'">
                <el-input type="password" v-model="dialogFormData.password" autocomplete="off"/>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="10">
            <el-upload
                class="avatar-uploader"
                action="/api/admin/avatar"
                :on-success="handleAvatarSuccess"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :headers="headers"
            >
              <div
                  v-if="dialogFormData.avatar"
                  class="avatar-img"
                  :style="'background-image: url('+dialogFormData.avatar+')'"
              >
                <div class="avatar-overlay">
                  <el-icon class="edit-icon">
                    <Edit/>
                  </el-icon>
                </div>
              </div>
              <div v-else class="avatar-placeholder">
                <el-icon class="upload-icon">
                  <Plus/>
                </el-icon>
                <span class="upload-text">点击上传头像</span>
              </div>
            </el-upload>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="doUpdate">
            确定
          </el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!--修改密码-->
  <div>
    <el-dialog v-model="editPwDialogVisible" title="修改密码" width="500">
      <el-form
          ref="editPwFormModel"
          style="max-width: 600px"
          :model="editPwForm"
          status-icon
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
      >
        <el-form-item label="账号" prop="age">
          <el-input v-model="editPwForm.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="原密码" prop="pass">
          <el-input v-model="editPwForm.oldPassword" type="password" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="新密码" prop="checkPass">
          <el-input
              v-model="editPwForm.newPassword"
              type="password"
              autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPass">
          <el-input
              v-model="editPwForm.confirmPassword"
              type="password"
              autocomplete="off"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="subEditPw">
            确认
          </el-button>
          <el-button @click="editPwDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<style scoped>
.demo-pagination-block {
  margin-top: 10px;
}

.search-region {
  float: left;
}

.addAdmin {
  float: left;
}

/* 头像上传区域 */
.avatar-uploader {
  width: 160px;
  height: 130px;
  margin-left: 25px;
  position: relative;
}

.avatar-uploader:hover {
  border-color: #409eff;
  background-color: #f0f7ff;
}

.avatar-img {
  width: 160px;
  height: 130px;
  border-radius: 8px; /* 圆角矩形 */
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  border: 1px solid #e4e4e4;
  transition: all 0.3s ease;
}

.uploaded-avatar:hover .avatar-overlay {
  opacity: 1; /* 悬停显示覆盖层 */
}

.edit-icon {
  color: white;
  font-size: 24px;
}

/* 未上传时的占位样式 */
.avatar-placeholder {
  width: 160px;
  height: 130px;
  border-radius: 8px;
  border: 2px dashed #dcdfe6; /* 虚线边框 */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
  transition: all 0.3s ease;
}

.avatar-placeholder:hover {
  border-color: #409eff; /* 悬停时边框变主题色 */
  color: #409eff;
}

.upload-icon {
  font-size: 28px;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 14px;
}

/* 头像样式 */
.AdImages {
  width: 60px;
  height: 60px;
  border-radius: 50%; /* 圆形头像 */
  background-size: cover; /* 覆盖方式显示，保持比例 */
  background-repeat: no-repeat;
  background-position: center;
  border: 2px solid #f0f0f0; /* 浅色边框 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 轻微阴影 */
  transition: transform 0.2s ease;
}

.AdImages:hover {
  transform: scale(1.05); /* 悬停放大效果 */
}
</style>